package user

import (
	"disk/service/user/dao"
	"disk/service/user/utils"
	"disk/utils/mysql"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"time"
)

type RegisterForm struct {
	Name     string `validate:"required,alphanum,min=3,max=50"`
	Email    string `validate:"required,email,max=50"`
	Password string `validate:"required"`
}

func Register(r *gin.RouterGroup) {
	r.POST("/register", func(c *gin.Context) {
		var form RegisterForm
		if err := c.ShouldBind(&form); err != nil {
			c.JSON(200, gin.H{
				"msg":  "数据校验未通过",
				"data": err.Error(),
				"code": 400,
			})
		} else {
			validate := validator.New()
			err := validate.Struct(form)
			if err != nil {
				c.JSON(200, gin.H{
					"msg":  "数据校验未通过，用户名只能包含数字和字母，邮箱需有效",
					"data": err.Error(),
					"code": 400,
				})
			} else {
				userList := dao.GetUserByName(form.Name)
				if len(userList) > 0 {
					c.JSON(200, gin.H{
						"msg":  "用户已经存在",
						"data": form.Name,
						"code": 400,
					})
				} else {
					var userData mysql.UserList
					userData.Name = form.Name
					userData.Email = form.Email
					userData.LockedUntil = time.Now()
					rawPassword, _ := utils.RsaDecode(form.Password)
					fmt.Println(rawPassword, len(rawPassword))
					if len(rawPassword) > 50 || len(rawPassword) < 8 {
						c.JSON(200, gin.H{
							"msg":  "密码长度需在8和50之间",
							"data": "",
							"code": 400,
						})
						return
					}
					userData.Password = utils.GetHash(rawPassword)
					result := dao.CreateUser(userData)
					if result.Error != nil {
						c.JSON(200, gin.H{
							"msg":  "注册失败",
							"data": result.Error,
							"code": 400,
						})
					} else {
						c.JSON(200, gin.H{
							"msg":  "注册成功",
							"data": userData.Name,
							"code": 200,
						})
					}
				}
			}
		}
	})
}
